import React, { useState, useEffect } from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  FlatList,
  Modal,
  TextInput,
  Alert,
  Image,
  ScrollView,
  Dimensions,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as ImagePicker from 'expo-image-picker';
import { TimeRecord } from '../types';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../types';
import { useTheme } from '../contexts/ThemeContext';

type HomeScreenNavigationProp = NativeStackNavigationProp<RootStackParamList>;

interface Task {
  id: string;
  title: string;
  coverImage: string;
  totalTimeToday: number; // 今日累计时间（分钟）
  isTracking: boolean;
  isPomodoroMode: boolean; // 新增字段
}

const DEFAULT_COVERS = [
  'https://picsum.photos/200/200?random=1',
  'https://picsum.photos/200/200?random=2',
  'https://picsum.photos/200/200?random=3',
  'https://picsum.photos/200/200?random=4',
];

const HomeScreen: React.FC = () => {
  const { colors } = useTheme();
  const navigation = useNavigation<HomeScreenNavigationProp>();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [newTaskTitle, setNewTaskTitle] = useState('');
  const [selectedCover, setSelectedCover] = useState(DEFAULT_COVERS[0]);
  const [isPomodoroMode, setIsPomodoroMode] = useState(false); // 新增状态
  const windowWidth = Dimensions.get('window').width;
  const cardWidth = (windowWidth - 40) / 2; // 40 = padding(20) * 2

  useEffect(() => {
    loadTasks();

    const unsubscribe = navigation.addListener('focus', () => {
      loadTasks();
    });

    return unsubscribe;
  }, [navigation]);

  const loadTasks = async () => {
    try {
      const savedTasks = await AsyncStorage.getItem('tasks');
      const savedRecords = await AsyncStorage.getItem('timeRecords');
      
      if (savedTasks) {
        let tasks: Task[] = JSON.parse(savedTasks);
        const records = savedRecords ? JSON.parse(savedRecords) : [];
        
        // 获取今天的日期
        const today = new Date().toISOString().split('T')[0];
        
        // 更新每个任务的今日时间
        tasks = tasks.map((task: Task) => {
          const todayRecord = records.find(
            (r: any) => r.taskId === task.id && r.date === today
          );
          return {
            ...task,
            totalTimeToday: formatDuration(todayRecord?.minutes || 0)
          };
        });
        
        setTasks(tasks);
        await AsyncStorage.setItem('tasks', JSON.stringify(tasks));
      }
    } catch (error) {
      Alert.alert('错误', '加载任务失败');
    }
  };

  const saveTasks = async (updatedTasks: Task[]) => {
    try {
      await AsyncStorage.setItem('tasks', JSON.stringify(updatedTasks));
    } catch (error) {
      Alert.alert('错误', '保存任务失败');
    }
  };

  const createNewTask = () => {
    if (!newTaskTitle.trim()) {
      Alert.alert('提示', '请输入任务名称');
      return;
    }

    const newTask: Task = {
      id: Date.now().toString(),
      title: newTaskTitle,
      coverImage: selectedCover,
      totalTimeToday: 0,
      isTracking: false,
      isPomodoroMode: isPomodoroMode, // 添加模式
    };

    const updatedTasks = [...tasks, newTask];
    setTasks(updatedTasks);
    saveTasks(updatedTasks);
    setModalVisible(false);
    setNewTaskTitle('');
    setSelectedCover(DEFAULT_COVERS[0]);
    setIsPomodoroMode(false);
  };

  const startTracking = (taskId: string) => {
    const task = tasks.find(t => t.id === taskId);
    if (task) {
      navigation.navigate('Timer', {
        taskId: task.id,
        taskTitle: task.title,
        coverImage: task.coverImage,
        isPomodoroMode: task.isPomodoroMode, // 传递模式信息
      });
    }
  };

  const formatDuration = (minutes: number) => {
    if (minutes < 1) return '0分钟';
    
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    
    const parts = [];
    if (hours > 0) parts.push(`${hours}小时`);
    if (mins > 0 || parts.length === 0) parts.push(`${mins}分钟`);
    
    return parts.join('');
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('提示', '需要访问相册权限来选择封面图片');
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [16, 9],
      quality: 0.8,
    });

    if (!result.canceled && result.assets[0].uri) {
      setSelectedCover(result.assets[0].uri);
    }
  };

  const deleteTask = async (taskId: string) => {
    Alert.alert(
      '确认删除',
      '确定要删除这个任务吗？相关的时间记录也会被删除。',
      [
        {
          text: '取消',
          style: 'cancel',
        },
        {
          text: '删除',
          style: 'destructive',
          onPress: async () => {
            try {
              // 删除任务
              const updatedTasks = tasks.filter(task => task.id !== taskId);
              await saveTasks(updatedTasks);
              setTasks(updatedTasks);

              // 删除相关的时间记录
              const savedRecordsStr = await AsyncStorage.getItem('timeRecords');
              if (savedRecordsStr) {
                const records = JSON.parse(savedRecordsStr);
                const updatedRecords = records.filter(
                  (record: { taskId: string }) => record.taskId !== taskId
                );
                await AsyncStorage.setItem('timeRecords', JSON.stringify(updatedRecords));
              }

              Alert.alert('成功', '任务已删除');
            } catch (error) {
              Alert.alert('错误', '删除任务失败');
            }
          },
        },
      ]
    );
  };

  const renderTaskItem = ({ item }: { item: Task }) => (
    <TouchableOpacity
      style={[
        styles.taskCard,
        {
          backgroundColor: colors.card,
          shadowColor: colors.text,
          borderColor: colors.border,
          borderWidth: StyleSheet.hairlineWidth,
          width: cardWidth,
        }
      ]}
      onPress={() => startTracking(item.id)}
      onLongPress={() => {
        Alert.alert(
          '任务操作',
          '请选择要执行的操作',
          [
            {
              text: '删除任务',
              style: 'destructive',
              onPress: () => deleteTask(item.id),
            },
            {
              text: '取消',
              style: 'cancel',
            },
          ]
        );
      }}
    >
      <Image 
        source={{ uri: item.coverImage }} 
        style={[styles.taskCover, { height: cardWidth * 0.75 }]} 
      />
      <View style={styles.taskInfo}>
        <Text style={[
          styles.taskTitle, 
          { 
            color: colors.text,
            fontSize: Math.min(cardWidth * 0.1, 16)
          }
        ]}>{item.title}</Text>
        <Text style={[
          styles.taskTime, 
          { 
            color: colors.textSecondary,
            fontSize: Math.min(cardWidth * 0.08, 14)
          }
        ]}>
          今日: {item.totalTimeToday || '0分钟'}
        </Text>
      </View>
      {item.isTracking && (
        <View style={[styles.trackingIndicator, { 
          backgroundColor: colors.card + 'CC',
          borderColor: colors.border,
          borderWidth: StyleSheet.hairlineWidth,
        }]}>
          <Ionicons 
            name="timer-outline" 
            size={Math.min(cardWidth * 0.12, 20)} 
            color={colors.primary} 
          />
        </View>
      )}
    </TouchableOpacity>
  );

  const modalContent = (
    <View style={[styles.modalContent, { backgroundColor: colors.card }]}>
      <ScrollView style={styles.modalScroll}>
        <Text style={[styles.modalTitle, { color: colors.text }]}>新建任务</Text>
        <TextInput
          style={[styles.input, { 
            borderColor: colors.border,
            color: colors.text,
            backgroundColor: colors.background
          }]}
          placeholder="任务名称"
          placeholderTextColor={colors.textSecondary}
          value={newTaskTitle}
          onChangeText={setNewTaskTitle}
        />

        <Text style={[styles.coverTitle, { color: colors.text }]}>选择封面</Text>
        
        <View style={styles.coverOptions}>
          <TouchableOpacity
            style={[styles.uploadButton, { borderColor: colors.primary }]}
            onPress={pickImage}
          >
            <Ionicons name="camera-outline" size={24} color={colors.primary} />
            <Text style={[styles.uploadButtonText, { color: colors.primary }]}>上传图片</Text>
          </TouchableOpacity>

          <Text style={[styles.orText, { color: colors.textSecondary }]}>或选择预设图片</Text>
          
          <ScrollView horizontal style={styles.coverList}>
            {DEFAULT_COVERS.map((cover, index) => (
              <TouchableOpacity
                key={index}
                onPress={() => setSelectedCover(cover)}
                style={[
                  styles.coverItem,
                  selectedCover === cover && { borderColor: colors.primary },
                ]}
              >
                <Image source={{ uri: cover }} style={styles.coverImage} />
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>

        <View style={styles.selectedCoverPreview}>
          <Text style={[styles.previewTitle, { color: colors.text }]}>封面预览</Text>
          <Image
            source={{ uri: selectedCover }}
            style={styles.coverPreview}
          />
        </View>

        <View style={styles.modeSelector}>
          <Text style={[styles.coverTitle, { color: colors.text }]}>选择模式</Text>
          <View style={styles.modeSwitchContainer}>
            <TouchableOpacity
              style={[
                styles.modeButton,
                !isPomodoroMode && { backgroundColor: colors.primary },
                { borderColor: colors.border }
              ]}
              onPress={() => setIsPomodoroMode(false)}
            >
              <Text style={[
                styles.modeButtonText,
                !isPomodoroMode ? { color: colors.card } : { color: colors.text }
              ]}>普通计时</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[
                styles.modeButton,
                isPomodoroMode && { backgroundColor: colors.primary },
                { borderColor: colors.border }
              ]}
              onPress={() => setIsPomodoroMode(true)}
            >
              <Text style={[
                styles.modeButtonText,
                isPomodoroMode ? { color: colors.card } : { color: colors.text }
              ]}>番茄钟</Text>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>

      <View style={styles.modalButtons}>
        <TouchableOpacity
          style={[styles.modalButton, { backgroundColor: colors.error }]}
          onPress={() => {
            setModalVisible(false);
            setNewTaskTitle('');
            setSelectedCover(DEFAULT_COVERS[0]);
          }}
        >
          <Text style={styles.modalButtonText}>取消</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.modalButton, { backgroundColor: colors.primary }]}
          onPress={createNewTask}
        >
          <Text style={styles.modalButtonText}>创建</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>
      <FlatList
        data={tasks}
        renderItem={renderTaskItem}
        keyExtractor={(item) => item.id}
        numColumns={2}
        columnWrapperStyle={styles.row}
        contentContainerStyle={[
          styles.taskList, 
          { 
            backgroundColor: colors.background,
            paddingHorizontal: 10 
          }
        ]}
        ListEmptyComponent={
          <View style={styles.emptyState}>
            <Text style={[
              styles.emptyStateText, 
              { 
                color: colors.textSecondary,
                fontSize: Math.min(windowWidth * 0.04, 16)
              }
            ]}>
              还没有任务，点击右上角添加
            </Text>
          </View>
        }
      />

      <Modal
        visible={modalVisible}
        animationType="slide"
        transparent={true}
        onRequestClose={() => setModalVisible(false)}
      >
        <View style={styles.modalContainer}>
          {modalContent}
        </View>
      </Modal>

      <TouchableOpacity
        style={[styles.fab, { backgroundColor: colors.primary }]}
        onPress={() => setModalVisible(true)}
      >
        <Ionicons name="add" size={24} color="white" />
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  taskList: {
    paddingVertical: 10,
  },
  taskCard: {
    flex: 1,
    backgroundColor: 'white',
    borderRadius: 12,
    marginHorizontal: 6,
    marginBottom: 12,
    overflow: 'hidden',
    elevation: 2,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
  },
  taskCover: {
    width: '100%',
    backgroundColor: '#f0f0f0',
  },
  taskInfo: {
    padding: 12,
  },
  taskTitle: {
    fontWeight: '600',
    marginBottom: 4,
  },
  taskTime: {
    color: '#666',
  },
  trackingIndicator: {
    position: 'absolute',
    top: 12,
    right: 12,
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    borderRadius: 12,
    padding: 4,
  },
  fab: {
    position: 'absolute',
    right: 16,
    bottom: 16,
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: '#007AFF',
    alignItems: 'center',
    justifyContent: 'center',
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 4,
  },
  modalContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    paddingHorizontal: 20,
  },
  modalContent: {
    backgroundColor: 'white',
    borderRadius: 12,
    width: '100%',
    maxHeight: '90%',
    overflow: 'hidden',
  },
  modalScroll: {
    padding: 20,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: '600',
    marginBottom: 16,
    textAlign: 'center',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 12,
    marginBottom: 16,
    fontSize: 16,
  },
  coverTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 12,
  },
  coverList: {
    flexDirection: 'row',
    marginBottom: 16,
  },
  coverItem: {
    marginRight: 12,
    borderRadius: 8,
    overflow: 'hidden',
    borderWidth: 2,
    borderColor: 'transparent',
  },
  selectedCover: {
    borderColor: '#007AFF',
  },
  coverImage: {
    width: 80,
    height: 80,
  },
  modalButtons: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 16,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: '#ddd',
  },
  modalButton: {
    flex: 1,
    padding: 14,
    borderRadius: 8,
    marginHorizontal: 8,
  },
  cancelButton: {
    backgroundColor: '#FF3B30',
  },
  confirmButton: {
    backgroundColor: '#007AFF',
  },
  modalButtonText: {
    color: 'white',
    textAlign: 'center',
    fontSize: 16,
    fontWeight: '600',
  },
  emptyState: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 32,
  },
  emptyStateText: {
    fontSize: 16,
    color: '#666',
  },
  coverOptions: {
    marginBottom: 16,
  },
  uploadButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 12,
    borderWidth: 1,
    borderColor: '#007AFF',
    borderRadius: 8,
    marginBottom: 12,
  },
  uploadButtonText: {
    color: '#007AFF',
    fontSize: 16,
    marginLeft: 8,
  },
  orText: {
    textAlign: 'center',
    color: '#666',
    marginVertical: 8,
  },
  selectedCoverPreview: {
    marginBottom: 16,
  },
  previewTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 8,
  },
  coverPreview: {
    width: '100%',
    height: 150,
    borderRadius: 8,
    backgroundColor: '#f0f0f0',
  },
  taskHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  deleteButton: {
    padding: 4,
  },
  modeSelector: {
    width: '100%',
    marginBottom: 16,
  },
  modeSwitchContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 8,
  },
  modeButton: {
    flex: 1,
    padding: 12,
    borderRadius: 8,
    alignItems: 'center',
    marginHorizontal: 4,
    borderWidth: 1,
  },
  modeButtonText: {
    fontSize: 16,
    fontWeight: '500',
  },
  row: {
    justifyContent: 'space-between',
    paddingHorizontal: 10,
  },
});

export default HomeScreen; 